/*
 * Copyright (C) 2010 mAPPn.Inc
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.mol.market.common.util;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;

import android.R.bool;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

import com.mol.market.Constants;
import com.mol.market.Session;
import com.mol.market.common.network.ApiAsyncTask.ApiRequestListener;
import com.mol.market.common.network.MarketAPI;
import com.mol.market.common.util.CashbackManager.CashbackTask;
import com.mol.market.fanli.ui.TaskInformationActivity.RebateTask;

/**
 * 本地应用状态监听器（安装、更新、卸载）
 * 
 * @author Andrew
 * @date 2011-7-28
 * 
 */
public class AppStatusReceiver extends BroadcastReceiver implements
		ApiRequestListener {
	private Session mSession;
	private String mPackageName;
	private Context mContext;

	@Override
	public void onReceive(Context context, Intent intent) {
		final String action = intent.getAction();
		mPackageName = intent.getData().getSchemeSpecificPart();
		mSession = Session.get(context);
		mContext = context;
		if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {

			mSession.removeInstalledApp(mPackageName);
			DBUtils.removeUpgradable(context, mSession, mPackageName);
			if (mSession.mNotSameApps.containsKey(mPackageName)) {
				Utils.installApk(context,
						new File(mSession.mNotSameApps.get(mPackageName)));
				// 2011/11/15 修复循环安装的问题
				mSession.mNotSameApps.remove(mPackageName);
			}
		} else if (Intent.ACTION_PACKAGE_REPLACED.equals(action)) {

			if ("com.mol.market".equals(mPackageName)) {
				AlarmManageUtils.notifyPushService(context, false);
			}
		} else if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
			mSession.addInstalledApp(mPackageName);
			if (mSession.isLogin()) {
				// 将应用标记为已经安装
				int updateCount = mSession.getDownloadManager()
						.completeInstallation(mPackageName,
								mSession.isAutoDelete());
				// 从市场下载 记录下载
				if (updateCount > 0) {
					mSession.setInstallPkg(mPackageName);
					MarketAPI.insertHistoryInstall(context, this,
							mSession.getInstallPkg());
				}
			}
			requestReward(context);
		}
	}

	/**
	 * 申请返利
	 */
	private void requestReward(final Context context) {

		if (mSession.cashbackManager == null) {
			// 非机锋市场返利平台安装的应用
			CashbackTask task = new CashbackTask();
			task.packageName = mPackageName;
			task.taskId = 0;
			task.status = RebateTask.STATUS_INSTALLED;
			task.source = CashbackTask.SOURCE_OTHERS;
			DBUtils.insertOrUpdateTask(context, task);
			return;
		}

		HashMap<String, CashbackTask> tasks = mSession.cashbackManager
				.getRebateTasks();

		CashbackTask task = new CashbackTask();
		task.packageName = mPackageName;
		if (tasks.containsKey(mPackageName)) {
			// 返利平台应用，直接打开进行激活
			Utils.openApk(context, mPackageName);
			task.source = CashbackTask.SOURCE_REBATE;
			task.status = RebateTask.STATUS_INSTALLED;
			DBUtils.insertOrUpdateTask(context, task);
		} else {
			// 非机锋市场返利平台安装的应用
			task.source = CashbackTask.SOURCE_OTHERS;
		}
		ArrayList<CashbackManager.CashbackTask> result = new ArrayList<CashbackManager.CashbackTask>();
		result.add(task);
		MarketAPI.reportInstallation(context, this, result);
	}

	@Override
	public void onSuccess(int method, Object obj) {

		// 提交成功，打开这个应用并变更任务状态
		switch (method) {

		case MarketAPI.ACTION_REPORT_INSTALLATION:

			mSession.cashbackManager.updateStatus(mPackageName,
					RebateTask.STATUS_INSTALLED);
			MarketAPI.requestReward(mContext, this, mPackageName);
			break;

		case MarketAPI.ACTION_REQUEST_REWARD:

			HashMap<String, Object> result = (HashMap<String, Object>) obj;
			String packageName = (String) result.get(Constants.KEY_PACKAGE);
			mSession.cashbackManager.updateStatus(packageName,
					RebateTask.STATUS_REBATED);
			break;
		case MarketAPI.ACTION_INSERT_HISTORY_INSTALL:
			mSession.setInstallPkg("");
			break;
		default:
			break;
		}
	}

	@Override
	public void onError(int method, int statusCode) {

		switch (method) {

		case MarketAPI.ACTION_REQUEST_REWARD:

			if (statusCode == 250) {
				mSession.cashbackManager.updateStatus(mPackageName,
						RebateTask.STATUS_INVALID);
			}
			break;
		default:
			break;
		}
	}

}
